Page({
  data: {
    activeIndex: 0,
    items: [],
    backgroundImg: '',
    headerImage: 'cloud://dp-6gydzcp27ac11774.6470-dp-6gydzcp27ac11774-1325695033/两带/两带.png',
    searchText: '',
    showSearchResults: false,
    searchResults: [],
    lastSearchIndex: -1,
    scrollIntoViewId:'',
    disableScrollHandler: false // 新增滚动处理锁
  },

  // 页面加载时执行
  async onLoad(options) {
    console.log('页面加载开始');
    await this.loadProjects(); // 等待数据加载完成
    await this.setBackground();
  
    // 确保数据已渲染到DOM
    await new Promise(resolve => wx.nextTick(resolve));
  
    // 处理参数
    if (options.name) {
      await this.handleScrollToName(options.name);
    }
    console.log('页面加载完成');
    
  },

  

  // 加载项目数据
  async loadProjects() {
    console.log('开始加载项目数据');
    wx.showLoading({ title: '加载中' });

    try {
      // 检查缓存
      const cache = wx.getStorageSync('projectsCache');
      if (cache?.data?.length > 0 && Date.now() - cache.timestamp < 3600000) {
        console.log('使用缓存数据');
        this.setData({
          items: cache.data,
          backgroundImg: cache.data[0]?.img || ''
        });
        return;
      }

      console.log('从云端加载数据');
      const res = await wx.cloud.callFunction({ name: 'getEcologyList' });
      console.log('云端数据加载成功', res);

      // 转换图片 URL
      const cloudFiles = res.result.map(item => item.img);
      const fileRes = await wx.cloud.getTempFileURL({ fileList: cloudFiles });
      console.log('图片 URL 转换成功', fileRes);

      // 映射数据
      const items = res.result.map((item, index) => ({
        ...item,
        img: fileRes.fileList[index]?.tempFileURL || ''
      }));
      console.log('数据映射完成', items);

      // 更新数据
      this.setData({
        items,
        backgroundImg: items[0]?.img || ''
      });

      // 存储缓存
      if (items.length > 0) {
        wx.setStorageSync('projectsCache', {
          timestamp: Date.now(),
          data: items
        });
        console.log('缓存数据存储成功');
      }

    } catch (err) {
      console.error('数据加载失败', err);
      wx.showToast({ title: '加载失败', icon: 'none' });
    } finally {
      wx.hideLoading();
      console.log('加载流程结束');
    }
  },

  // 设置背景图
  setBackground() {
    console.log('设置背景图');
    if (this.data.items.length > 0) {
      this.setData({
        activeIndex: 0,
        backgroundImg: this.data.items[0].img
      });
      console.log('背景图设置为项目图片');
    } else {
      this.setData({
        backgroundImg: this.data.headerImage
      });
      console.log('背景图设置为默认图片');
    }
  },


  // 滚动事件处理
onScroll(e) {
  if (this.data.disableScrollHandler) return; // 如果禁用滚动处理，直接返回

  // console.log('滚动事件触发');
  const query = wx.createSelectorQuery();
  this.data.items.forEach((item, index) => {
    query.select(`#item-${index}`).boundingClientRect();
  });
  query.selectViewport().scrollOffset();
  query.exec((res) => {
    const scrollOffset = res[res.length - 1].scrollTop;
    let newIndex = -1;

    // console.log('当前滚动位置', scrollOffset);

    // 查找当前滚动位置对应的项目
    for (let i = 0; i < res.length - 1; i++) {
      const itemRect = res[i];
      const itemTop = itemRect.top - 200;
      const itemBottom = itemTop + itemRect.height;

      if (scrollOffset >= itemTop && scrollOffset < itemBottom) {
        newIndex = i;
        break;
      }
    }

    if (newIndex !== this.data.activeIndex) {
      this.setData({
        activeIndex: newIndex,
        backgroundImg: newIndex >= 0 ? this.data.items[newIndex].img : this.data.backgroundImg
      });
      console.log('更新背景图到索引', newIndex);
    }
  });
},

  // 点击图片
  onItemTap(e) {
    console.log('点击图片事件触发');
    const index = e.currentTarget.dataset.index;
    this.setData({
      activeIndex: index,
      backgroundImg: this.data.items[index].img
    });
    console.log('背景图更新为索引', index);
  },

  // 点击文字预览图片
  onItemDesc(e) {
    console.log('点击文字预览图片');
    const index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.items[index].img,
      urls: this.data.items.map(item => item.img),
      success: () => {
        console.log('图片预览成功');
      },
      fail: (error) => {
        console.error('图片预览失败', error);
      },
      complete: () => {
        console.log('图片预览完成');
      }
    });
  },

  // 预览全景图片
  previewHeaderImage() {
    console.log('预览全景图片');
    wx.cloud.getTempFileURL({
      fileList: [this.data.headerImage],
      success: res => {
        console.log('获取临时链接成功', res);
        const tempUrl = res.fileList[0].tempFileURL;
        wx.previewImage({
          current: tempUrl,
          urls: [tempUrl]
        });
      },
      fail: err => {
        console.error('获取临时链接失败', err);
        wx.showToast({ title: '图片加载失败', icon: 'none' });
      }
    });
  },

  // 搜索结果输入处理
  onSearchInput(e) {
    console.log('搜索输入事件触发');
    this.setData({
      searchText: e.detail.trim(),
      showSearchResults: false
    });
  },

  //清空输入框
  onClear(){
    console.log('清空事件触发');
    this.setData({   
      searchText:"",
     
    })
  },

  // 处理搜索
  // 处理搜索（补充防抖和状态控制）
async handleSearch() {
  const keyword = this.data.searchText.trim();
  if (!keyword) {
    wx.showToast({ title: '请输入关键词', icon: 'none' });
    return;
  }

  wx.showLoading({ title: '搜索中...', mask: true });

  try {
    const results = this.data.items.filter(item =>
      item.text.toLowerCase().includes(keyword.toLowerCase())
    );

    if (results.length === 0) {
      wx.showToast({ title: '无结果', icon: 'none' });
      return;
    }

    const targetIndex = this.data.items.findIndex(item => item._id === results[0]._id);
    console.log('targetIndex查询',targetIndex );

    this.setData({
      activeIndex: targetIndex,
      showSearchResults: true,
      searchResults: results,
      lastSearchIndex: targetIndex,
      backgroundImg: this.data.items[targetIndex].img,
      // 关键修改：设置滚动目标ID
      scrollIntoViewId: `item-${targetIndex}`,
      // disableScrollHandler:false
    }, () => {
      wx.nextTick(() => {
        // 重置滚动ID确保下次搜索可再次触发
        setTimeout(() => {
          this.setData({ 
            scrollIntoViewId: '',
            // disableScrollHandler:true
          });
          console.log('查询精确滚动完成', targetIndex);
        }, 2000); // 匹配动画时长
        wx.hideLoading();
      });
    });

  } catch (error) {
    // ...错误处理保持不变
    console.error('搜索异常', error);
    wx.hideLoading();
    wx.showToast({ title: '搜索失败', icon: 'none' });
  }
},


// 新增处理name参数的方法 精确查询处理方法（独立维护）
async handleScrollToName(name) {
  console.log('[精确滚动] 启动参数:', name);
  this.setData({ disableScrollHandler: true });

  // 确保数据加载完成
  if (this.data.items.length === 0) {
    await this.loadProjects();
    await new Promise(resolve => setTimeout(resolve, 100)); // 确保渲染完成
  }

  const keyword = decodeURIComponent(name).trim().toLowerCase();
  if (!keyword) return;

  // 模糊匹配逻辑
  const targetItem = this.data.items.find(item => 
    item.text.trim().toLowerCase().includes(keyword)
  );

  if (!targetItem) {
    console.warn('未找到匹配项:', name);
    return;
  }

  const targetIndex = this.data.items.indexOf(targetItem);
  console.log('目标索引:', targetIndex);

  // 使用手动滚动
  const query = wx.createSelectorQuery();
  query.select(`#item-${targetIndex}`).boundingClientRect();
  query.selectViewport().scrollOffset();
  query.exec(res => {
    if (res[0]) {
      const itemTop = res[0].top;
      const currentScrollTop = res[1].scrollTop;
      wx.pageScrollTo({
        scrollTop: currentScrollTop + itemTop - 100,
        duration: 500,
        success: () => {
          this.setData({
            activeIndex: targetIndex,
            backgroundImg: this.data.items[targetIndex].img,
            searchResults: [targetItem],
          lastSearchIndex: targetIndex,
          backgroundImg: targetItem.img,
          disableScrollHandler: false ,
          // 关键修改：设置滚动目标ID
          scrollIntoViewId: `item-${targetIndex}`,
          },() => {
            wx.nextTick(() => {
              // 重置滚动ID确保下次搜索可再次触发
              setTimeout(() => {
                this.setData({ scrollIntoViewId: '' });
                console.log('查询精确滚动完成', targetIndex);
              }, 3000); // 匹配动画时长
              wx.hideLoading();
            });
          });
        }
      });
    }
  });
}






});